//
//  CZComPoseViewController.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComPoseViewController: UIViewController, UITextViewDelegate {
// MARK: ------懒加载控件------
	//右侧按钮
	private lazy var rightButton: UIButton = {
	let button = UIButton()
	button.setTitle("发送", forState: .Normal)
		button.titleLabel?.font = UIFont.systemFontOfSize(15)
		//设置背景图片
		button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
		button.addTarget(self, action: #selector(CZComPoseViewController.click), forControlEvents: .TouchUpInside)
		button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
		
		button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
		
		//设置文字颜色
		button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
		button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
		button.frame.size = CGSize(width: 45, height: 30)

		//在这里指定按钮状态不起作用,原因是我们的按钮被UIBarButtonItem控制着
		//		button.enabled = false
		return button
	}()
	
	//自定义 uitextView
	private lazy var textView: CZComposeTextView = {
	let view = CZComposeTextView()
		//设置字体大小
		view.font = UIFont.systemFontOfSize(14)
		//设置代理
		
	view.delegate = self
		view.placeHoder = "请输入内容"
		view.alwaysBounceVertical = true
	return view
	}()
	
	private lazy var toolbar: CZComposeToolBar = {
	let view = CZComposeToolBar(frame: CGRectZero)
	return view
	}()
	//配图
	private lazy var picture: CZComposePictureView = {
	let views = CZComposePictureView()
	views.backgroundColor = self.view.backgroundColor
	return views
	}()
	
	//自定义标签键盘
	private lazy var emtioconKeyBrad: CZEmoticonKeyBoard = {
	let vv = CZEmoticonKeyBoard()
		//设置大小
		vv.size = CGSize(width: self.textView.width, height: 216)
	return vv
	}()
	private lazy var titleView: UILabel = {
	let label = UILabel(textColor: UIColor.darkGrayColor(), fontSIze: 17)
//
		
		if let name = CZUserAccountViewModel.shareUserAccount.userAccount?.name {
			let title: String = "发微博\n\(name)"
			
			//获取name 在文本里的范围
			let range = (title as NSString).rangeOfString(name)
			
			let attributedStr = NSMutableAttributedString(string: title)
			//修改颜色
			attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
			
			attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13), range: range)
			label.attributedText = attributedStr
		
		} else {
		label.text = "发微博"
		
		}

		//多行显示
		label.numberOfLines = 0
		label.textAlignment = .Center
		label.sizeToFit()
	return label
	}()
	
    override func viewDidLoad() {
        super.viewDidLoad()
		
		//监听
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComPoseViewController.keyBoardShow(_:)), name:  UIKeyboardWillChangeFrameNotification, object: nil)
		
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComPoseViewController.didSectedEmoticon(_:)), name: DidSeletedEmoticonNotification, object: nil)
        // Do any additional setup after loading the view.
		
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CZComPoseViewController.didSeletedDeleteEmiticon), name: DidSeletedDeleteEmoticonButtonNotification, object: nil)
		
		setUpUI()
    }
	// MARK: ------监听删除表情按钮------
	@objc private func didSeletedDeleteEmiticon() {
	//删除文本的内容
		textView.deleteBackward()
	
	}
	
	// MARK: ------监听表情按钮点击------
	@objc private func didSectedEmoticon(noti: NSNotification) {
		guard let emoticon = noti.object as? CZEmoticon else {
		return
		}
		
		textView.insertEmticon(emoticon, fontSize: textView.font!)
		
		
		//以下代码抽取到分类
		
//		print(emoticon?.type)
//		if emoticon.type == "0" {
////			textView.insertText(emoticon.chs!)
//			//记录上一次的副文本
//			let orginaAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//			
//			//1.根据表情图片路径创建一个 uiimage
//			let image = UIImage(named: emoticon.path!)
//			// 2.根据 uiiimage 创建一个 NSTextAttachment() 文本附件
//			let attachtment = NSTextAttachment()
//			attachtment.image = image
//			//取到字体的高度
//			let fontHeight = textView.font!.lineHeight
//			
//			attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//			//3 根据NSTextAttachment创建一个NSAttributedString副文本
//			let attr = NSAttributedString(attachment: attachtment)
//			//获取 textview的选中范围
//			var range = textView.selectedRange
//			//替换选中的字符串
//			orginaAttr.replaceCharactersInRange(range, withAttributedString: attr)
//			
//			//追加副文本
//			//orginaAttr.appendAttributedString(attr)
//			//设置副文本的字体大小
//			orginaAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, orginaAttr.length))
//			
//			textView.attributedText = orginaAttr
//			//每次点击表情开始位置+1
//			range.location += 1
//			//设置选中范围长度为0
//			range.length = 0
//			//设置选中范围
//			textView.selectedRange = range
//
//		}
//		else {
//		textView.insertText((emoticon.code! as NSString).emoji()!)
//			
//		}
		
//		textView.insertEmoticon(emoticon)
		
		
	}
// MARK: ------键盘监听------
	
	@objc private func keyBoardShow(noti: NSNotification) {
		let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
		
		let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
		
		toolbar.snp_updateConstraints { (make) in
			make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
	UIView.animateWithDuration(animationDuration) {
		//更新约束
		
		}
		}
		
	}
	
	func scrollViewWillBeginDragging(scrollView: UIScrollView) {
		self.view.endEditing(true)
	}
	
	private func setUpUI() {
	setUpNav()
		view.addSubview(textView)
		view.addSubview(toolbar)
		textView.addSubview(picture)
		
		picture.snp_makeConstraints { (make) in
			make.top.equalTo(textView).offset(100)
			make.centerX.equalTo(textView)
			make.width.equalTo(textView).offset(-20)
			make.height.equalTo(textView.snp_width).offset(-20)
		}
		
		textView.snp_makeConstraints { (make) in
			make.top.equalTo(view)
			make.leading.equalTo(view)
			make.trailing.equalTo(view)
			make.bottom.equalTo(toolbar.snp_top)
		}
		
		toolbar.snp_makeConstraints { (make) in
			make.leading.equalTo(view)
			make.trailing.equalTo(view)
			make.bottom.equalTo(view)
			make.height.equalTo(44)
		}
		
		toolbar.didSeletedButonClosure = { [weak self]
			(type: CZComposeToolBarButtonType) in
			switch type {
			case .Picture:
				self!.didSelectedPicutre()
			case .Mention:
				print("2")
				case .Trend:
				print("3")
				case .Emoticun:
				self?.didSelectedEmticon()
				
				case .Add:
				print("5")
			}
		
		}
		//点击图片按钮回调
		picture.didSelectAddImageClouse = {
		[weak self] in
			self?.didSelectedPicutre()
		}
//	view.backgroundColor = RandomColor()
	}

	//关于导航栏视图设置
	private func setUpNav() {
	 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: #selector(CZComPoseViewController.cancleAction))
	
		navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
		 navigationItem.rightBarButtonItem?.enabled = false
		//自定义 titleView
		navigationItem.titleView = titleView
	}
	
	// MARK: ------点击事件------
	@objc private func cancleAction() {
		self.view.endEditing(true)
	dismissViewControllerAnimated(true, completion: nil)
	
	}
	
	@objc private func click() {
		
		//获取表情文本附件
		//在指定范围内 遍历副文本的属性
//		var result = ""
//		textView.attributedText.enumerateAttributesInRange( NSMakeRange(0, textView.attributedText.length), options: []) { (infoDic, range, _) in
//			if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
//			//就是文本附件
//			let chs = attachment.emoticon?.chs!
//				result += chs!
//			} else {
//			//文本
//				let text = self.textView.attributedText.attributedSubstringFromRange(range).string
//				result += text
//			}
//		}
		
		
		if picture.images.count > 0 {
			upload()
		} else {
			updata()
		}
		
		
	}
	
	private func updata() {
	let accesstoken = CZUserAccountViewModel.shareUserAccount.accessToken!
		let status = textView.emticonText
		
		SVProgressHUD.show()
		//请求发送微博接口
		 CZNetWorkTools.sharedTools.update(accesstoken, status: status) { (response, error) in
			if error != nil {
			SVProgressHUD.showErrorWithStatus("网络请求异常")
			return
			} else {
				SVProgressHUD.showSuccessWithStatus("发送成功")
			self.dismissViewControllerAnimated(true, completion: nil)
				
			}
			
		}
	
	}
//发送带图片微博请求
	private func upload() {
		let accesstoken = CZUserAccountViewModel.shareUserAccount.accessToken!
		let status = textView.emticonText
		
		SVProgressHUD.show()
		//动用发图片微博接口
		let image = picture.images.first!
		
		//请求发送微博接口
		CZNetWorkTools.sharedTools.upload(accesstoken, status: status, image: image) { (response, error) in
			if error != nil {
			SVProgressHUD.showErrorWithStatus("网络异常")
				return
			} else {
				SVProgressHUD.showSuccessWithStatus("发送成功")
				self.dismissViewControllerAnimated(true, completion: nil)
				
			}
		}
	}

	
	// MARK: ------text代理------
	func textViewDidChange(textView: UITextView) {
		navigationItem.rightBarButtonItem?.enabled = textView.hasText()
		
	}
	
	deinit{
	NSNotificationCenter.defaultCenter().removeObserver(self)
	}
	
}

extension CZComPoseViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
	func didSelectedEmticon(){
		//
		if textView.inputView == nil {
			//设置标签键盘
			textView.inputView = emtioconKeyBrad
			toolbar.showEmoticonIcon(true)
		} else {
		//设置系统键盘
		textView.inputView = nil
			//设置表情键盘
			toolbar.showEmoticonIcon(false)
		}
		//获取第一响应者
	textView.becomeFirstResponder()
		
		//重新加载自定义 inputView
		textView.reloadInputViews()
	}
	// 点击图片的操作
	func didSelectedPicutre() {
		let pictur = UIImagePickerController()
		//是否支持这种类型
		pictur.delegate = self
		if UIImagePickerController.isSourceTypeAvailable(.Camera) {
			pictur.sourceType = .Camera
			
		} else {
		pictur.sourceType = .PhotoLibrary
		
		}
		
		if UIImagePickerController.isCameraDeviceAvailable(.Front) {
			
		} else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
		
		} else {
		
		
		}
		//可以编辑
//		pictur.allowsEditing = true
		presentViewController(pictur, animated: true, completion: nil)
	
		
	}
	
	
	func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
		
//		let data = UIImagePNGRepresentation(image)
//		data?.writeToFile("/Users/zyahs/Desktop/1.png", options: true)
		
		
		let scaleImage = image.scaleImageWithWidth(300)
		
		picture.addImae(scaleImage)
		picker.dismissViewControllerAnimated(true, completion: nil)
		
	}
	
	func imagePickerControllerDidCancel(picker: UIImagePickerController) {
		picker.dismissViewControllerAnimated(true, completion: nil)
	}
	
}














